oldMyChoice=[];
window.onload = async function() {
  //页面加载完成 执行 同步操作 获取  全部全部班级列表

   let majorInfo={list:[]};
   let res0= new Promise(function (resolve, reject){
      axios.post('api/getAllmajor').then(res=>{
          res=res.data;
          if (res.error_code==0){
              resolve(res.data)
          }
          reject(res)
      })
  })
    await res0.then(res=>{
        majorInfo.list=res;
    })


  // var allOptions = ['VR虚拟现实','游戏设计与开发','网络安全运维','PHP全栈工程师','UI设计','JAVA大数据','大数据']
  var allOptions = majorInfo.list.map(item=>item.dir_name)

  //console.log(allOptions)


  var myChoice = []
  var second = []

  var stuid = (location.search.slice(location.search.indexOf('=') + 1))
  var times = 0
  try {
    s = JSON.parse(decodeURIComponent(atob(stuid)))
    if (typeof(s) !== 'object') {
      location.href = '/login'
    }
  } catch (err) {
    location.href = '/login'
  }
  if (stuid == ' ' || stuid == '' || stuid == null) {
    location.href = '/login'
  }

  $('#stuId_Name').html(s.stu_id + '   ' + s.name)
  $('#userInfo-nickName').html(s.stu_id + '   ' + s.name)


  axios.defaults.headers.common.token = localStorage.getItem('stu_token')



  //添加 我的选择
  function addBadges() {
    myChoice=myChoice.filter(item=>item)
    $('#my-choice .item').remove()
    for (let i in myChoice) {

      let elem = `
        <h4 class=" d-block d-sm-inline-block m-2 item">
            <span class=" badge badge-success pl-2 pt-3 pb-3 pr-1 d-flex justify-content-sm-between">
                <span class="badge badge-light ">${Number(i)+1}</span>
                <span>${myChoice[i]}</span>
                <span style="margin: auto" ></span>
                 <span class="badge del-btns badge-dark"  >X</span>
            </span>
        </h4>
        `
      $('#my-choice').append(elem)
    }

    $(".del-btns").click(function() {
      let index = $(".del-btns").index(this);
      let btnDis = $($('#fangxiang .card-deck button')[allOptions.indexOf(myChoice[index])])
      btnDis.removeAttr('disabled')
      del(myChoice[index])
    });

  }

  axios.get('api/config').then(function(res) {
    config = res.data
    //console.log(config)
    // 获取学生填报填报的所有专业
    axios.get('/api/stu/self').then(function(res) {
      //console.log(res)
      // 填报的次数
      times = res.data.wished_times
      if (res.data.wish !== null) {
        myChoice = Object.values(res.data.wish) //当前学生的志愿
        myChoice=myChoice.filter(item=>item)
        oldMyChoice=JSON.parse(JSON.stringify(myChoice))
        //console.log(myChoice)
        for (item in res.data.wish) {
          //console.log(res.data.wish[item])
          if (!res.data.wish[item]) {
            continue
          }
          //console.log(res.data.wish[item])
          second.push(config.classlist[res.data.wish[item]])

          index = allOptions.indexOf(config.classlist[res.data.wish[item]])
          $(`button[index=${index}]`).attr('disabled', '1')
        }
        addBadges()
      }
      if (res.data.wished_times >= 1 && res.data.wished_times < 3) {
        $('#saveVolunteer').attr('edit', '1')
        $('#saveVolunteer').html('修改志愿')
        $('#saveVolunteer').removeClass('btn-primary')
        $('#saveVolunteer').addClass('btn-danger')
      } else if (res.data.wished_times == 3) {
        $('#saveVolunteer').removeClass('btn-primary')
        $('#saveVolunteer').addClass('btn-secondary')
        $('#saveVolunteer').addClass('disabled')
      }

      // 加载志愿
      loadMajor()
    })
  })







  function removeByValue(arr, value) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] == value) {
        return arr.splice(i, 1)
      }
    }
  }






  function del(value) {
    index = allOptions.indexOf(value)
      $($(`button`)[index]).removeAttr('disabled')

    myChoice.splice(myChoice.indexOf(value), 1)

    // $('.choice-item').remove()
    //console.log(myChoice)
    addBadges() // 重新渲染
  }
  // 修改志愿单击事件
  $('#saveVolunteer').on('click', function() {

    if (myChoice.length != allOptions.length) {
      alert('志愿数不足！！')
      return
    }
      if (!oldMyChoice){
          oldMyChoice=[];
      }
    if(JSON.stringify(oldMyChoice)==JSON.stringify(myChoice)){
      alert('当前志愿顺序与之前相同，操作无效！')
      return
    }
    conf = confirm('你只有' + (3 - times) + '次修改志愿的机会了，确认修改吗？')
    if (!conf) {
      return
    }
    $(this).addClass('disabled')
    values = Object.values(config.classlist)
    keys = Object.keys(config.classlist)
    //console.log(myChoice)
    let wish={}
    for (let i in myChoice) {
      wish['wish'+(Number(i)+1)]=myChoice[i]
    }
    axios.post('/api/stu/wish', {
      stu_id: s.stu_id,
      wish
    }).then(function(res) {
      //console.log(res)
      if (res.data.error) {
        alert(res.data.error)
        $('#saveVolunteer').removeClass('disabled')
      } else if (res.data.warning) {
        alert(res.data.warning)
        $('#saveVolunteer').removeClass('disabled')
      } else {
        $('#saveVolunteer').removeClass('disabled')
        if (times == 0) {
          $('#saveVolunteer').attr('edit', '1')
          $('#saveVolunteer').html('修改志愿')
          $('#saveVolunteer').removeClass('btn-primary')
          $('#saveVolunteer').addClass('btn-danger')
        } else if (times == 2) {
          $('#saveVolunteer').removeClass('btn-dangerx')
          $('#saveVolunteer').addClass('btn-dark')
          $('#saveVolunteer').addClass('disabled')
        }
        alert(res.data.message)
        times += 1
      }
    })

  })

  // 加载志愿
  function loadMajor() {
    axios.get('/api/stu/peoplecount')
      .then(function(res) {
        //console.log(res.data)
        //console.log($('#fangxiang .card-deck'))
        $('#fangxiang .card-deck1 *').remove()
        for (let i in allOptions) {
          let {capacity,nowcount}=res.data[allOptions[i]];
          let isDisabled=(myChoice.indexOf(allOptions[i])!=-1)//存在则为true
          let elem = `
            <div class="card-wrap col-6 col-sm-3" style="margin-top: 15px" >
                  <div class="card  " >
                    <img src="${majorInfo.list[i].dir_coverUrl}" class="card-img-top" alt="${allOptions[i]}">
                    <div class="card-body">
                      <h5 class="card-title text-center">${allOptions[i]}</h5>
                      <div class="progress mb-2">
                        <div class="progress-bar bg-secondary"
                         id="${allOptions[i]}Progress" role="progressbar"
                         aria-valuenow="30" aria-valuemin="0" aria-valuemax="100"
                         style="width:${
                           nowcount==0?'0':nowcount>=capacity?'100':(nowcount/capacity)*100
                         }%;"
                         ></div>
                      </div>
                      <button type="button" ${isDisabled?'disabled':''} class="btn btn-success w-100" id="add-${allOptions[i]}">选择</button>
                    </div>
                  </div>
              </div>
              `
          $('#fangxiang .card-deck1').append(elem)
        }
        $('#fangxiang button').click(function() {
          let index = $('#fangxiang  button').index(this);
          if (allOptions[index]) {
            if (myChoice.indexOf(allOptions[index]) != -1) {
              alert('志愿重复')
              //console.log('请检查代码')
              return
            }
            myChoice.push(allOptions[index])
            $(this).attr('disabled', '1')
            addBadges()
          }
        })
      })
  }



}

function logOut(){
    delete localStorage.stu_token;
    window.location.href='/'
}

